package io.renren.modules.nuaa.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import io.renren.common.exception.RenException;
import io.renren.modules.nuaa.controller.TCertificateController;
import io.renren.modules.nuaa.dto.TCategoryDTO;
import io.renren.modules.nuaa.dto.TCertificateDTO;
import io.renren.modules.nuaa.entity.TCategoryEntity;
import io.renren.modules.nuaa.excel.TCertificateExcel;
import io.renren.modules.nuaa.service.TCategoryService;
import io.renren.modules.nuaa.service.TCertificateService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Scope("prototype")
public class TCertificateListener extends AnalysisEventListener<TCertificateExcel> {

    @Autowired
    private TCategoryService tCategoryService;

    @Autowired
    private TCertificateService tCertificateService;

    @Override
    public void invoke(TCertificateExcel tCertificateExcel, AnalysisContext analysisContext) {

        TCertificateDTO tCertificateDTO = new TCertificateDTO();

        String categoryName = tCertificateExcel.getCategoryName();
        TCategoryEntity tCategoryEntity = null;
        if(StringUtils.isNotBlank(categoryName)){
            tCategoryEntity = tCategoryService.queryByName(categoryName);
            if(tCategoryEntity == null){
                throw new RenException("分类名称有误");
            }
        }else{
            throw new RenException("分类名称为空");
        }
        Boolean isExist = tCertificateService.queryByConditions(tCategoryEntity.getId().intValue(),
                tCertificateExcel.getIdCard(),
                tCertificateExcel.getCertificateNo());

        if(isExist){
            tCertificateDTO.setName(tCertificateExcel.getName());
            tCertificateDTO.setIdCard(tCertificateExcel.getIdCard());
            tCertificateDTO.setCertificateNo(tCertificateExcel.getCertificateNo());
            tCertificateDTO.setCategoryId(tCategoryEntity.getId().intValue());
            tCertificateDTO.setCreateDate(new Date());
            tCertificateDTO.setExpirationDate(tCertificateExcel.getExpirationDate());

            tCertificateService.save(tCertificateDTO);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
